<template>
  <div>
    <van-cell
      v-for="(item, index) in hightLightSuggestions"
      :key="index"
      icon="search"
      @click="$emit('update-keywords',suggestions[index])"
    >
      <template #title>
        <span v-html="item"></span>
      </template>
    </van-cell>
  </div>
</template>

<script>
/**
 * 当keywods发生变化的时候
 * 1.先渲染搜索建议组件
 * 2.监视keywords发生变化,请求搜索建议
 */
import { getSuggestionsAPI } from '@/api/search'
import { debounce } from 'lodash'
export default {
  data() {
    return {
      suggestions: []
    }
  },
  props: {
    keywords: {
      type: String,
      required: true
    }
  },
  watch: {
    //监视属性有3种方法
    //1.函数式
    //2.对象
    //3.在methods找方法名
    keywords: {
      handler: 'getSuggestions',
      immediate: true
    }
  },
  methods: {
    getSuggestions: debounce(async function () {
      const { data } = await getSuggestionsAPI(this.keywords)
      this.suggestions = data.data.options.filter((item) => item !== null)
    }, 300)
  },
  computed: {
    hightLightSuggestions() {
      const reg = new RegExp(this.keywords, 'ig')
      return this.suggestions.map((str) => {
        return str.replace(
          reg,
          (match) => `<span style="color:red">${match}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
